package com.aaa.sso.util;

import com.aaa.common.bo.Member;
import com.aaa.sso.service.RemoteMemberService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @fileName:MyRealm
 * @description:
 * @author:zhz
 * @createTime:2020/12/7 10:53
 * @version:1.0.0
 */
public class MemberRealm extends AuthorizingRealm {

    @Autowired
    private RemoteMemberService remoteMemberService;

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
       //获取登录会员信息 (用户名)
        String userName = (String)authenticationToken.getPrincipal();
        //调用远程接口 获取会员信息
        Member member = remoteMemberService.queryByUserName(userName);
        if(member==null){
            //抛出账号异常（用户名错误）
            throw new AccountException();

        }
        //第一个参数  会员信息   第2参数 加密密码
        // 第3参数 ByteSource  盐值封装的ByteSource    第4个 当前realm的名称
        return new SimpleAuthenticationInfo(member,member.getPassword(),
                ByteSource.Util.bytes(member.getPwSalt()),this.getName());
    }


}
